/**=========================================================
 * Service: utils.js
 * Utility library to use across the theme
 =========================================================*/

App.service('Utils', ["$window", "APP_MEDIAQUERY", "BACKEND_PATH", 
    function($window, APP_MEDIAQUERY, BACKEND_PATH) {
        'use strict';
        
        var $html = angular.element("html"),
            $win  = angular.element($window),
            $body = angular.element('body');
            
        return {
            // DETECTION
            support: {
                transition: (function() {
                    var transitionEnd = (function() {

                        var element = document.body || document.documentElement,
                            transEndEventNames = {
                                WebkitTransition: 'webkitTransitionEnd',
                                MozTransition: 'transitionend',
                                OTransition: 'oTransitionEnd otransitionend',
                                transition: 'transitionend'
                            }, name;

                        for (name in transEndEventNames) {
                            if (element.style[name] !== undefined) return transEndEventNames[name];
                        }
                    }());

                    return transitionEnd && { end: transitionEnd };
                })(),
                animation: (function() {
                    var animationEnd = (function() {
                        var element = document.body || document.documentElement,
                            animEndEventNames = {
                                WebkitAnimation: 'webkitAnimationEnd',
                                MozAnimation: 'animationend',
                                OAnimation: 'oAnimationEnd oanimationend',
                                animation: 'animationend'
                            }, name;

                        for (name in animEndEventNames) {
                            if (element.style[name] !== undefined) return animEndEventNames[name];
                        }
                    }());

                    return animationEnd && { end: animationEnd };
                })(),
                requestAnimationFrame: window.requestAnimationFrame ||
                                    window.webkitRequestAnimationFrame ||
                                    window.mozRequestAnimationFrame ||
                                    window.msRequestAnimationFrame ||
                                    window.oRequestAnimationFrame ||
                                    function(callback){ 
                                        window.setTimeout(callback, 1000/60); 
                                    },
                touch: (
                    ('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
                    (window.DocumentTouch && document instanceof window.DocumentTouch)  ||
                    (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) || //IE 10
                    (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0) || //IE >=11
                    false
                ),
                mutationobserver: (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver || null)
            },
            // UTILITIES
            isInView: function(element, options) {

                var $element = $(element);

                if (!$element.is(':visible')) {
                    return false;
                }

                var window_left = $win.scrollLeft(),
                    window_top  = $win.scrollTop(),
                    offset      = $element.offset(),
                    left        = offset.left,
                    top         = offset.top;

                options = $.extend({topoffset:0, leftoffset:0}, options);

                if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
                    left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
                    return true;
                } else {
                    return false;
                }
            },
            
            langdirection: $html.attr("dir") == "rtl" ? "right" : "left",
            
            isTouch: function () {
                return $html.hasClass('touch');
            },
            
            isSidebarCollapsed: function () {
                return $body.hasClass('aside-collapsed');
            },
            
            isSidebarToggled: function () {
                return $body.hasClass('aside-toggled');
            },
            
            isMobile: function () {
                return $win.width() < APP_MEDIAQUERY.tablet;
            },
            
//==============================================通用操作======================================================      
            /**
             * 获取后台请求地址
             */  
            getBackendPath: function(relativePath){
                return BACKEND_PATH + relativePath;
            },

            /**
             * 获取非分页查询的相对路径
             */
            getQueryListUrl: function(){
                return '/common/queryList'
            },
            
            /**
             * 获取分页查询的相对路径
             */
            getQueryPageUrl: function(){
                return '/common/queryPage'
            },
              
            /**
             * 判定是否为空
             */   
            isEmpty: function(obj){
                return obj == null || obj === "" || obj === 'undefined' || obj === undefined || obj.length === 0;
            },

            /**
             * 返回第一个非空值
             */ 
            coalesce: function(){
                for (var i = 0; i < arguments.length; i++) {
                    if (!this.isEmpty(arguments[i]))
                        return arguments[i];
                }
            },
            
            /**
             * 判定是否为年、年月或年月日
             */   
            isTimeStr: function(str){
                var reg1 = /\d{4}-\d{2}-\d{2}/,
                    reg2 = /\d{4}-\d{2}/,                
                    reg3 = /[A-Za-z]{3}.\d{4}/;
                return reg1.test(str) || reg2.test(str) || reg3.test(str);
            },
            
            getLanguage: function(){
                return localStorage.NG_TRANSLATE_LANG_KEY;
            },
            
            clone: function(obj) {
                if (typeof obj == "function" || Object(obj) !== obj) {
                    return obj;
                }
                
                var res = new obj.constructor;
                
                for (var key in obj) {
                    res[key] = this.clone(obj[key]);
                }
                return res;
            },

            setChildValByStr: function(obj,path,value){
                var paths = path.split("."),
                    level = paths.length;
                switch(level) {
                    case 1:
                        obj[paths[0]] = value;
                        break;
                    case 2:
                        obj[paths[0]][paths[1]] = value;
                        break;
                    case 3:
                        obj[paths[0]][paths[1]][paths[2]] = value;
                        break;
                    case 4:
                        obj[paths[0]][paths[1]][paths[2]][paths[3]] = value;
                        break;
                    case 5:
                        obj[paths[0]][paths[1]][paths[2]][paths[3]][paths[4]] = value;
                        break;
                }
            },
//==============================================数字操作======================================================
            /**
             * 增加千分位符
             */
            numberFormat: function(value){
                if (this.isEmpty(value)) return value;
                
                var intValue, decValue, symbol = '', result = '',
                    strValue = value.toString();
                
                if (strValue.indexOf('-') > -1){
                    symbol = '-';
                    strValue = strValue.substring(1,strValue.length);
                }
                
                if (strValue.indexOf('.') > -1) {
                    intValue = strValue.substring(0,strValue.indexOf('.'));
                    decValue = strValue.substring(strValue.indexOf('.'))
                } else{
                    intValue = strValue;
                    decValue = '';
                }
                while (intValue.length > 3) {
                    result = ',' + intValue.slice(-3) + result;
                    intValue = intValue.slice(0, intValue.length - 3);
                } 
                
                result = symbol + intValue + result + decValue; 
                
                return result;
            },         
//==============================================时间操作======================================================    
            /**
             * 判定日期字符串
             */  
            isDateString: function(str){			
                var date = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,	
                    month = /^[0-9]{4}-[0-9]{2}$/,	
                    year = /^[0-9]{4}$/;	
                return date.test(str) || month.test(str) || year.test(str);
            },
            
            /**
             *  日期格式化 
             */      
            dateFormat: function(date,format){
                if (date instanceof Date){
                    var o = {   
                        "M+" : date.getMonth() + 1,                 //月份   
                        "d+" : date.getDate(),                    //日   
                        "h+" : date.getHours(),                   //小时   
                        "m+" : date.getMinutes(),                 //分   
                        "s+" : date.getSeconds(),                 //秒   
                        "q+" : Math.floor((date.getMonth() + 3) / 3), //季度   
                        "S"  : date.getMilliseconds()             //毫秒   
                    };   
                    if(/(y+)/.test(format))   
                        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));   
                    for(var k in o){
                        if(new RegExp("("+ k +")").test(format)){
                            format = format.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                        }
                    }
                    return format;
                }else{
                    return date;
                }
            },
            
            /**
             *  判断闰年
             */
            isLeapYear: function(date) {
                var year = date.getFullYear();
                return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
            },
            
            /**
             *  日期的加减操作
             */
            addDate: function(date, interval, value){
                var returnDate = new Date(date.getTime());
                if (value) {
                    switch(interval.toLowerCase()) {
                        case 'second':
                            returnDate.setTime(date.getTime() + value * 1000);
                            break;
                        case 'minute':
                            returnDate.setTime(date.getTime() + value * 60 * 1000);
                            break;
                        case 'hour':
                            returnDate.setTime(date.getTime() + value * 60 * 60 * 1000);
                            break;
                        case 'day':
                            returnDate.setDate(date.getDate() + value);
                            break;
                        case 'month':
                            returnDate.setMonth(date.getMonth() + value);
                            break;
                        case 'year':
                            returnDate.setFullYear(date.getFullYear() + value);
                            break;
                    }
                }

                return returnDate;
            },

            /**
             *  获取日期的季度
             */
            getQuarter: function(date){
                var month = date.getMonth() + 1;
                if(month <= 3) return 1
                else if (month <= 6) return 2
                else if (month <= 9) return 3
                else return 4
            },
            
            /**
             * 将字符型转成Date型
             */
            strToDate: function(dateStr,format){
                var dateParseStr;
                if (format == 'yyyy-MM-dd'){
                    dateParseStr = dateStr.replace(/-/g, "/");
                }else if (format == 'yyyyMMdd'){
                    dateParseStr = dateStr.substr(0,4) + '/' + dateStr.substr(4,2) + '/' + dateStr.substr(6,2);
                }
                return new Date(Date.parse(dateParseStr));
            },

            /**
             * 获取一周的第一天 即周六
             */
            getStartDayOfWeek: function(date){
                return date.getDay() == 6 ? date : this.addDate(date,'day',(date.getDay() + 1) * -1);
            },
//================================================数组操作============================================ 
            /**
             *  合并数组
             */           
            mergeArray: function(array1, array2, etc){
                var array = []

                for (var i = 0; i < arguments.length; i++) {
                    array = array.concat(arguments[i]);
                }
                
                return array;     
            },
            
            /**
             * 从数组中删除
             */
            removeFromArray: function(array,target,key){
                if (angular.isObject(target)){
                    for (var i = 0; i < array.length; i++){
                        if (array[i][key] === target[key]){
                            array.splice(i, 1);
                        }
                    }
                }else{
                    for (var i = 0; i < array.length; i++){
                        if (array[i] === target){
                            array.splice(i, 1);
                        }
                    }
                }
            },
            
            /**
             * 数组转化成字符串
             */
            arrayToString: function(array,separate){
                var result = "";
                if (!this.isEmpty(array)){
                    
                    if (this.isEmpty(separate)){
                        separate = ",";
                    }
                    
                    for (var i = 0; i < array.length; i++){
                        result += array[i] + separate;
                    }
                    return result.substring(0,result.length - 1);
                }

                return result;
            },
            
            /**
             * 数组中是否包含
             */
            isArrayContains: function(array,obj){
                if (this.isEmpty(array)){
                    return false;
                }
                
                for (var i = 0; i < array.length; i++){
                    if (array[i] == obj){
                        return true;
                    }
                }
                
                return false;
            },

//================================================表格操作============================================ 
            /**
             * 行合并
             */
            handleRowspan: function(column,datas){
                if (this.isEmpty(datas) || datas.length < 0) return datas;

                var index = 0;
                datas[0][column + "_rowSpan"] = 1;
                for (var i = 1; i < datas.length; i++){
                    if (datas[i][column] == datas[index][column]){
                        datas[index][column + "_rowSpan"] = datas[index][column + "_rowSpan"] + 1;
                        datas[i][column + "_rowSpan"] = -1;
                    }else{
                        datas[i][column + "_rowSpan"] = 1;
                        index = i;
                    }
                }

                return datas;
            }   
        };
    }
]);